﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace SnippetBox.Core.Common.Mvc.HtmlHelpers {
    public static class NavigationExtensions {
        public static string CurrentClassWhen(this HtmlHelper html, string actionName) {
            return CurrentClassWhen(html, new {action = actionName});
        }        
        
        public static string CurrentClassWhen(this HtmlHelper html, string actionName, string controllerName) {
            return CurrentClassWhen(html, new { action = actionName, controller = controllerName });
        }
        
        public static string CurrentClassWhen(this HtmlHelper html, string actionName, string controllerName, string areaName) {
            return CurrentClassWhen(html, new { action = actionName, controller = controllerName, area = areaName });
        }

        public static string CurrentClassWhen(this HtmlHelper html, object routeValues, string className = "current") {
            RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
            var currentRouteValues = html.ViewContext.RequestContext.RouteData.Values;
            bool currentUrl = true;
            
            foreach (var key in routeValueDictionary.Keys) {
                if (!currentRouteValues.ContainsKey(key)) {
                    currentUrl = false;
                    continue;
                }

                var specifiedValue = routeValueDictionary[key].ToString();
                var currentValue = currentRouteValues[key].ToString();

                if (!specifiedValue.Equals(currentValue, StringComparison.OrdinalIgnoreCase))
                    currentUrl = false;
            }
            
            if (currentUrl)
                return className;

            return string.Empty;
        }
    }
}
